package fire.db;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import fire.common.Jdbc;

public class MySqlJdbc {
	private static String dbname = "hot";
	private static String ip = "localhost";
	private static String host = "3306";
	private static String username = "root";
	private static String password = "root";

	private static String driver = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://" + ip + ":" + host + "/"
			+ dbname + "?characterEncoding=utf8";
	private static List<Connection> connList;
	private static int defaultCount = 10;

	/**
	 * 初始化list
	 */
	static {
		if (null == connList) {
			connList = new ArrayList<>();
		}
	}

	/**
	 * 获得默认链接方式
	 * 
	 * @return
	 */
	public static Connection getConn() {
		return getConn(defaultCount);
	}

	/**
	 * 自定义链接数量链接
	 * 
	 * @param count
	 * @return
	 */
	public static Connection getConn(int count) {
		if (!connList.isEmpty()) {
			Connection conn = connList.get(0);
			connList.remove(0);
			return conn;
		} else {
			connList = getConnList(count);
			return getConn(count);
		}
	}

	/**
	 * 创建多个链接集合
	 * 
	 * @param count
	 * @return
	 */
	private static List<Connection> getConnList(int count) {
		if (count > 0) {
			for (int i = 0; i < count; i++) {
				Connection conn = Jdbc.getConn(driver, url, username, password);
				connList.add(conn);
			}
		} else {
			Connection conn = Jdbc.getConn(driver, url, username, password);
			connList.add(conn);
		}
		return connList;
	}

	public static void main(String[] args) {
		for (int i = 0; i < 1000; i++) {
			// getConn(10);
			System.out.println(getConn(10));
		}
	}
}
